package com.anysoft.utils;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import com.anysoft.StaticField;
import com.anysoft.base.BaseActivity;
import com.anysoft.other.SplashNewActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by wwq on 2017/1/3.
 * 拼接地址的工具
 */

public class HttpUtils {

    /**
     * 根据给定的请求接口url与参数创建请求地址，带默认参数
     *
     * @param url    请求接口地址
     * @param params 如果没有参数则传null
     * @return
     */
    public static String createRequestUrl(Context context, String url, Map<String, String> params) {
        String requestUrl = createRequestUrl(url, params);
        requestUrl = requestUrl + (requestUrl.endsWith("?") ? "" : "&") + getCommonParams2String(context);
        return requestUrl;
    }

    /**
     * 根据给定的请求接口url与参数创建请求地址，不带默认参数
     *
     * @param url    请求接口地址
     * @param params 如果没有参数则传null
     * @return
     */
    public static String createRequestUrl(String url, Map<String, String> params) {
        if (params == null) {
            params = new HashMap<>();
        }

        // 按照key做排序
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuffer paramsSB = new StringBuffer();

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (!TextUtils.isEmpty(params.get(key))) {
                paramsSB.append((i == 0 ? "" : "&") + key + "=" + value);
            }
        }
        return url + (url.endsWith("?") ? "" : "?") + paramsSB.toString();
    }

    /**
     * 公共参数
     *
     * @return
     */
    public static Map<String, String> getCommonParams(Context context, Map<String, String> requestParams) {
        Map<String, String> params = new HashMap<>();
        params.put("merchantId", "GY");
        params.put("channel", "1");
        params.put("user_type", "p");
        if (!TextUtils.isEmpty(StaticField.token)) {
            params.put("token", StaticField.token);
        }
        params.put("version", StaticField.getVersionName(context));
        params.put("uuid", getMD5(SplashNewActivity.UUID));
        params.put("platform", "Android");
        params.put("Mac", getAdresseMAC(context));
        params.put("phone_type", android.os.Build.MANUFACTURER + ":" + android.os.Build.MODEL);
        params.put("appChannel", StaticField.getChannel(context));

        if (requestParams != null) {
            params.putAll(requestParams);
        }
        return params;
    }

    /**
     * 公共参数
     *
     * @return
     */
    public static String getCommonParams2String(Context context) {

        String param = "merchantId=GY&channel=1&user_type=p";
        if (!TextUtils.isEmpty(StaticField.token)) {
            param += "&token=" + StaticField.token;
        }
        param += "&version=" + StaticField.getVersionName(context) + "&uuid="
                + getMD5(SplashNewActivity.UUID) + "&platform=Android&Mac=" + getAdresseMAC(context)
                + "&phone_type=" + android.os.Build.MANUFACTURER + ":" + android.os.Build.MODEL
                + "&appChannel=" + StaticField.getChannel(context);
        return param;
    }

    public static String getCommonParams2StringByWeb(Context context) {

        String param = "merchantId=GY&channel=1&user_type=p";
        String token = (TextUtils.isEmpty(StaticField.token)) ? "" : StaticField.token;
        param += "&token=" + token;
        param += "&version=" + StaticField.getVersionName(context) + "&uuid="
                + getMD5(SplashNewActivity.UUID) + "&platform=Android&Mac=" + getAdresseMAC(context)
                + "&phone_type=" + android.os.Build.MANUFACTURER + ":" + android.os.Build.MODEL
                + "&appChannel=" + StaticField.getChannel(context);
        param += "&isDataPerfect=" + ((BaseActivity) context).isUserDataPerfect();
        param += "&havePhoneNumber=" + ((BaseActivity) context).isHavePhoneNumber();
        return param;
    }

    /**
     * 获取MAC地址
     *
     * @param mContext
     * @return
     */
//    public static String getMacAddress(Context mContext) {
//        String macStr = "";
//        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        if (wifiInfo.getMacAddress() != null) {
//            macStr = wifiInfo.getMacAddress();// MAC地址
//        } else {
//            macStr = "null";
//        }
//
//        return macStr;
//    }

    private static final String marshmallowMacAddress = "02:00:00:00:00:00";
    private static final String fileAddressMac = "/sys/class/net/wlan0/address";

    public static String getAdresseMAC(Context context) {
        WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInf = wifiMan.getConnectionInfo();

        if (wifiInf != null && marshmallowMacAddress.equals(wifiInf.getMacAddress())) {
            String result = null;
            try {
                result = getAdressMacByInterface();
                if (result != null) {
                    return result;
                } else {
                    result = getAddressMacByFile(wifiMan);
                    return result;
                }
            } catch (IOException e) {
                Log.e("MobileAccess", "Erreur lecture propriete Adresse MAC");
            } catch (Exception e) {
                Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
            }
        } else {
            if (wifiInf != null && wifiInf.getMacAddress() != null) {
                return wifiInf.getMacAddress();
            } else {
                return "00-00-00-00-00-00";
            }
        }
        return marshmallowMacAddress;
    }

    private static String getAddressMacByFile(WifiManager wifiMan) throws Exception {
        String ret;
        int wifiState = wifiMan.getWifiState();

        wifiMan.setWifiEnabled(true);
        File fl = new File(fileAddressMac);
        FileInputStream fin = new FileInputStream(fl);
        ret = crunchifyGetStringFromStream(fin);
        fin.close();

        boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
        wifiMan.setWifiEnabled(enabled);
        return ret;
    }

    private static String crunchifyGetStringFromStream(InputStream crunchifyStream) throws IOException {
        if (crunchifyStream != null) {
            Writer crunchifyWriter = new StringWriter();

            char[] crunchifyBuffer = new char[2048];
            try {
                Reader crunchifyReader = new BufferedReader(new InputStreamReader(crunchifyStream, "UTF-8"));
                int counter;
                while ((counter = crunchifyReader.read(crunchifyBuffer)) != -1) {
                    crunchifyWriter.write(crunchifyBuffer, 0, counter);
                }
            } finally {
                crunchifyStream.close();
            }
            return crunchifyWriter.toString();
        } else {
            return "No Contents";
        }
    }

    private static String getAdressMacByInterface() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (nif.getName().equalsIgnoreCase("wlan0")) {
                    byte[] macBytes = nif.getHardwareAddress();
                    if (macBytes == null) {
                        return "";
                    }

                    StringBuilder res1 = new StringBuilder();
                    for (byte b : macBytes) {
                        res1.append(String.format("%02X:", b));
                    }

                    if (res1.length() > 0) {
                        res1.deleteCharAt(res1.length() - 1);
                    }
                    return res1.toString();
                }
            }

        } catch (Exception e) {
            Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
        }
        return null;
    }

    public static String getMD5(String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            return toHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    // String to byte
    public static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F'};

    public static String random32() {
        String strRand = "";
        for (int i = 0; i < 32; i++) {
            strRand += String.valueOf((int) (Math.random() * 10));
        }
        MentorLogger.Loge("============"+strRand);
        return strRand;
    }

}
